package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.mapper.PatientMapper;
import com.qf.pojo.PatientPojo;
import com.qf.service.PatientService;
import com.qf.utils.Constant;
import com.qf.utils.GetDate;
import com.qf.utils.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class PatientServiceImpl extends ServiceImpl<PatientMapper, PatientPojo> implements PatientService {
    @Autowired
    PatientMapper patientMapper;

    @Override
    public ResultMsg findAll(Integer currentPage, Integer pageSize) {
        currentPage = currentPage <= 0 ? 1 : currentPage;
        pageSize = pageSize <= 0 ? 20 : pageSize;
        QueryWrapper<PatientPojo> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", Constant.NO_DELETE);
        Page<PatientPojo> patientPojoPage = new Page<>(currentPage, pageSize);
        Page<PatientPojo> all = patientMapper.findAll(patientPojoPage, wrapper);
        return ResultMsg.SUCCESS(all);
    }

    @Override
    public ResultMsg findAllByKeyWords(String keyWords, Integer currentPage, Integer pageSize) {
        currentPage = currentPage <= 0 ? 1 : currentPage;
        pageSize = pageSize <= 0 ? 20 : pageSize;
        QueryWrapper<PatientPojo> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", Constant.NO_DELETE);
        wrapper.and(queryWrapper -> queryWrapper.like("patient_name", keyWords).or().like("patient_id", keyWords).or().like("patient_tel", keyWords));
        Page<PatientPojo> patientPojoPage = new Page<>(currentPage, pageSize);
        Page<PatientPojo> all = patientMapper.findAll(patientPojoPage, wrapper);
        return ResultMsg.SUCCESS(all);
    }

    @Override
    public ResultMsg findAllByDoctorId(Integer userId, Integer currentPage, Integer pageSize) {
        currentPage = currentPage <= 0 ? 1 : currentPage;
        pageSize = pageSize <= 0 ? 20 : pageSize;
        QueryWrapper<PatientPojo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("is_delete", Constant.NO_DELETE);
        Page<PatientPojo> patientPojoPage = new Page<>(currentPage, pageSize);
        Page<PatientPojo> all = patientMapper.findAll(patientPojoPage, wrapper);
        return ResultMsg.SUCCESS(all);
    }

    @Override
    public ResultMsg findAllByDate(String startTimeStr, String endTimeStr, Integer currentPage, Integer pageSize) {
        startTimeStr += " 00:00:00";
        endTimeStr += " 23:59:59";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = simpleDateFormat.parse(startTimeStr);
            endTime = simpleDateFormat.parse(endTimeStr);
            currentPage = currentPage <= 0 ? 1 : currentPage;
            pageSize = pageSize <= 0 ? 20 : pageSize;

            QueryWrapper<PatientPojo> wrapper = new QueryWrapper<>();
            wrapper.between("patient_date", new Timestamp(startTime.getTime()), new Timestamp(endTime.getTime()));
            wrapper.eq("is_delete", Constant.NO_DELETE);
            Page<PatientPojo> patientPojoPage = new Page<>(currentPage, pageSize);
            Page<PatientPojo> all = patientMapper.findAll(patientPojoPage, wrapper);
            return ResultMsg.SUCCESS(all);
        } catch (ParseException e) {
            return ResultMsg.FAILED(Constant.LZY + 4, "日期格式异常");
        }

    }

    @Override
    @Transactional
    public ResultMsg addPatient(PatientPojo patient) {
        if (patient.getPatientName().equals("-1"))
            return ResultMsg.FAILED(Constant.LZY + 1, "患者姓名不能为空");
        if (patient.getPatientTel().equals("-1"))
            return ResultMsg.FAILED(Constant.LZY + 1, "患者手机号不能为空");
        if (patient.getPatientStatus() != 0 && patient.getPatientStatus() != 1)
            return ResultMsg.FAILED(Constant.LZY + 1, "患者状态参数异常");
        if (this.getOne(new QueryWrapper<PatientPojo>().eq("patient_tel", patient.getPatientTel())) != null)
            return ResultMsg.FAILED(Constant.LZY + 1, "患者手机号已被注册");
        String substring = UUID.randomUUID().toString().replace("-", "").substring(0, 10);
        PatientPojo onePatient = this.getOne(new QueryWrapper<PatientPojo>().eq("patient_id", substring));
        while (onePatient != null) {
            substring = UUID.randomUUID().toString().replace("-", "").substring(0, 10);
            onePatient = this.getOne(new QueryWrapper<PatientPojo>().eq("patient_id", substring));
        }
        patient.setPatientId(substring);
        patient.setPatientStatus(0);
        patient.setIsDelete(Constant.NO_DELETE);
        patient.setPatientDate(new Timestamp(new Date().getTime()));
        boolean save = this.save(patient);
        if (save)
            return ResultMsg.SUCCESS(patient);
        return ResultMsg.FAILED(Constant.LZY + 2, "未知错误");
    }

    @Override
    @Transactional
    public ResultMsg modifyDoctorForPatient(String patientId, Integer userId) {
        QueryWrapper<PatientPojo> wrapper = new QueryWrapper<>();
        wrapper.eq("patient_id", patientId);
        PatientPojo one = this.getOne(wrapper);
        one.setUserId(userId);
        boolean update = this.updateById(one);
        if (update)
            return ResultMsg.SUCCESS();
        return ResultMsg.FAILED(Constant.LZY + 2, "未知错误");
    }

    @Override
    @Transactional
    public ResultMsg deletePatientByPatientId(String patientId) {
        QueryWrapper<PatientPojo> wrapper = new QueryWrapper<>();
        wrapper.eq("patient_id", patientId);
        PatientPojo one = this.getOne(wrapper);
        one.setIsDelete(Constant.DELETED);
        boolean update = this.updateById(one);
        if (update)
            return ResultMsg.SUCCESS();
        return ResultMsg.FAILED(Constant.LZY + 2, "未知错误");
    }

    @Override
    public ResultMsg login(String patientName, String patientTel, HttpServletRequest request) {
        QueryWrapper<PatientPojo> wrapper = new QueryWrapper<>();
        wrapper.eq("patient_name", patientName);
        wrapper.eq("patient_tel", patientTel);
        List<PatientPojo> list = this.list(wrapper);
        if (list.size() == 0)
            return ResultMsg.FAILED(Constant.LZY + 1, "用户名或密码错误");
        HttpSession session = request.getSession();
        session.setAttribute(Constant.PATIENT_SESSION, list.get(0));
        return ResultMsg.SUCCESS(list.get(0));
    }

    @Override
    public ResultMsg register(String patientName, String patientTel) {

        if (this.getOne(new QueryWrapper<PatientPojo>().eq("patient_tel", patientTel)) != null)
            return ResultMsg.FAILED(Constant.LZY + 1, "您的手机号已被注册");
        PatientPojo patientPojo = new PatientPojo();
        String substring = UUID.randomUUID().toString().replace("-", "").substring(0, 10);
        PatientPojo onePatient = this.getOne(new QueryWrapper<PatientPojo>().eq("patient_id", substring));
        while (onePatient != null) {
            substring = UUID.randomUUID().toString().replace("-", "").substring(0, 10);
            onePatient = this.getOne(new QueryWrapper<PatientPojo>().eq("patient_id", substring));
        }
        patientPojo.setPatientId(substring);
        patientPojo.setPatientName(patientName);
        patientPojo.setPatientTel(patientTel);
        boolean save = this.save(patientPojo);
        if (save)
            return ResultMsg.SUCCESS(patientPojo);
        return ResultMsg.FAILED(Constant.LZY + 1, "注册失败");
    }

    @Override
    public ResultMsg logout(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            session.setAttribute(Constant.PATIENT_SESSION, null);
            return ResultMsg.SUCCESS();
        } catch (Exception e) {
            return ResultMsg.FAILED(Constant.LZY + 2, e.getMessage());
        }
    }

    @Override
    public ResultMsg findByDay(Integer patientStatus) {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = sdf.format(GetDate.getTimesmorning(calendar));
        String endTime = sdf.format(GetDate.getTimesnight(calendar));
        QueryWrapper<PatientPojo> wrapper = new QueryWrapper<>();
        if (patientStatus != -1)
            wrapper.eq("patient_status", patientStatus);
        wrapper.between("patient_date", startTime, endTime);
        wrapper.eq("is_delete", Constant.NO_DELETE);
        List<PatientPojo> list = this.list(wrapper);
        if (list != null) {
            return ResultMsg.SUCCESS(list);
        }
        return ResultMsg.FAILED(Constant.LZY + 2, "未知错误");
    }

    @Override
    public ResultMsg findByStatus(Integer patientStatus) {
        QueryWrapper<PatientPojo> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", Constant.NO_DELETE);
        if (patientStatus != -1)
            wrapper.eq("patient_status", patientStatus);
        List<PatientPojo> list = this.list(wrapper);
        return ResultMsg.SUCCESS(list);
    }

    @Override
    public ResultMsg updatePatientStatus(String patientId) {
        QueryWrapper<PatientPojo> wrapper = new QueryWrapper<>();
        wrapper.eq("patient_id", patientId);
        wrapper.eq("is_delete", Constant.NO_DELETE);
        PatientPojo one = this.getOne(wrapper);
        one.setPatientStatus(2);
        boolean update = this.updateById(one);
        if (update)
            return ResultMsg.SUCCESS(one);
        return ResultMsg.FAILED(Constant.LZY + 1, "修改失败");
    }
}
